#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
错误对话框模块
显示详细的错误信息
"""

import logging
import traceback
from typing import Optional

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QTextEdit, QDialogButtonBox, QPushButton,
                              QApplication)
from PySide6.QtGui import QFont, QIcon
from core.i18n import tr


# 初始化日志记录器
logger = logging.getLogger("error_dialog")


class ErrorDialog(QDialog):
    """错误对话框，显示详细的错误信息"""
    
    def __init__(self, title: str, message: str, detail: Optional[str] = None, 
                parent=None):
        """初始化错误对话框
        
        Args:
            title: 对话框标题
            message: 错误消息
            detail: 详细错误信息
            parent: 父窗口
        """
        super().__init__(parent)
        self.setWindowTitle(title)
        self.resize(600, 400)
        self._init_ui(message, detail)
        
    def _init_ui(self, message: str, detail: Optional[str]):
        """初始化UI
        
        Args:
            message: 错误消息
            detail: 详细错误信息
        """
        # 主布局
        layout = QVBoxLayout(self)
        
        # 错误图标和消息
        header_layout = QHBoxLayout()
        
        # 错误图标
        icon_label = QLabel()
        icon_label.setFixedSize(32, 32)
        # 使用系统的错误图标或自定义图标
        header_layout.addWidget(icon_label)
        
        # 错误消息
        message_label = QLabel(message)
        message_label.setWordWrap(True)
        message_label.setTextFormat(Qt.RichText)
        font = QFont()
        font.setPointSize(10)
        message_label.setFont(font)
        header_layout.addWidget(message_label, 1)
        
        layout.addLayout(header_layout)
        
        # 详细信息
        if detail:
            # 详细信息标签
            detail_label = QLabel(tr("error_dialog_details", "详细信息:"))
            detail_label.setAlignment(Qt.AlignLeft)
            layout.addWidget(detail_label)
            
            # 详细信息文本框
            detail_edit = QTextEdit()
            detail_edit.setReadOnly(True)
            detail_edit.setPlainText(detail)
            
            # 使用等宽字体
            font = QFont("Courier New", 9)
            detail_edit.setFont(font)
            
            layout.addWidget(detail_edit)
            
            # 复制按钮
            copy_button = QPushButton(tr("error_dialog_copy", "复制详细信息"))
            copy_button.clicked.connect(lambda: self._copy_to_clipboard(detail))
            layout.addWidget(copy_button)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok)
        button_box.accepted.connect(self.accept)
        
        layout.addWidget(button_box)
        
    def _copy_to_clipboard(self, text: str):
        """复制文本到剪贴板
        
        Args:
            text: 要复制的文本
        """
        clipboard = QApplication.clipboard()
        clipboard.setText(text)


def show_error(title: str, message: str, detail: Optional[str] = None, 
              parent=None) -> None:
    """显示错误对话框
    
    Args:
        title: 对话框标题
        message: 错误消息
        detail: 详细错误信息
        parent: 父窗口
    """
    # 记录错误
    logger.error(f"{title}: {message}")
    if detail:
        logger.debug(detail)
        
    # 显示对话框
    dialog = ErrorDialog(title, message, detail, parent)
    dialog.exec_()


def show_exception(title: str, message: str, exception: Exception, 
                  parent=None) -> None:
    """显示异常错误对话框
    
    Args:
        title: 对话框标题
        message: 错误消息
        exception: 异常对象
        parent: 父窗口
    """
    # 获取异常栈跟踪
    detail = f"{tr('error_exception_type', '异常类型')}: {type(exception).__name__}\n"
    detail += f"{tr('error_exception_message', '异常消息')}: {str(exception)}\n\n"
    detail += f"{tr('error_stack_trace', '栈跟踪')}:\n"
    detail += traceback.format_exc()
    
    # 显示错误对话框
    show_error(title, message, detail, parent)
